package com.snopy.concurrency.park;

import com.snopy.concurrency.base.FIFOMutex;
import lombok.extern.slf4j.Slf4j;

import java.sql.Time;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.LockSupport;

/**
 * @author snopy
 * @version 1.0.0
 * @classname ParkDemo
 * @description
 * @email 77912204@qq.com
 * @date 2022/06/23 22:53
 */

@Slf4j
public class ParkDemo {
    static int num = 0;
    public static void main(String[] args) throws InterruptedException {
        /*FIFOMutex lock = new FIFOMutex();

        Thread t1 = new Thread(()->{
            log.info("挂起......");
            lock.lock();
            num++;
        });
        Thread t2 = new Thread(()->{
            log.info("挂起......");
            lock.lock();
            num--;
        });
        t1.start();
        t2.start();
        TimeUnit.MILLISECONDS.sleep(100);
        log.info("放飞......");
        //list.unpark();
        log.info("over......");*/
        Thread t1 = new Thread(() -> {
            log.info("t1 park...{}",Thread.currentThread().isInterrupted());

            LockSupport.park();
            log.info("t1 park2...{}",Thread.currentThread().isInterrupted());
        }, "t1");
//        Thread t2 = new Thread(() -> {
//            LockSupport.park();
//        }, "t1");
        t1.start();
        TimeUnit.SECONDS.sleep(1);
        log.info("t1 park...{}",Thread.currentThread().isInterrupted());
        t1.interrupt();
        log.info("t1 park2...{}",Thread.currentThread().isInterrupted());
        //LockSupport.unpark(t1);
    }

}
@Slf4j
class ParkTool{
    private boolean flag = false;
    public void pause(){
        while (!canProceed()){
            LockSupport.park(this);
            log.info("paused... thread state:{}",Thread.currentThread().getState());
        }
    }
    //at most
    private boolean canProceed(){
        log.info("current thread state:{}",Thread.currentThread().getState());
        return flag;
    }
    public void unPark(){
        flag = true;
        log.info("thread state:{},unpark current thread......",Thread.currentThread().getState());
        LockSupport.unpark(Thread.currentThread());
    }
}